package main

import (
	"context"
	"fmt"
	"time"

	"github.com/go-redis/redis/v8"
)

var rdb *redis.Client

func main() {
	rdb = redis.NewClient(&redis.Options{
		Addr:     "10.0.0.161:6379",
		Password: "",
		DB:       0,
	})

	setAndGet()

	lockAndUnlock()
}

func lockAndUnlock() {
	ctx := context.Background()

	lockKey := "lock_key"

	// lock
	resp := rdb.SetNX(ctx, lockKey, 1, time.Second*30)
	lockSuccess, err := resp.Result()
	if err == nil && lockSuccess {
		fmt.Println("lock success!")

		// do something

		// unlock
		delResp := rdb.Del(ctx, lockKey)
		unlockSuccess, err := delResp.Result()
		if err == nil && unlockSuccess > 0 {
			fmt.Println("unlock success!")
		} else {
			fmt.Println("unlock failed!", err)
		}
	} else {
		fmt.Println("did not get the lock")
	}
}

func setAndGet() {
	key := "name"
	ctx := context.Background()
	if err := rdb.Set(ctx, key, "zhang", time.Second*3).Err(); err != nil {
		panic("set error")
	}

	val, err := rdb.Get(ctx, key).Result()
	if err == redis.Nil {
		panic("key does not exist")
	} else if err != nil {
		panic(err)
	} else {
		fmt.Println(key, val)
	}
}
